package ren.xxpure.controller;

import io.swagger.annotations.ApiOperation;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import ren.xxpure.entity.CommonResult;
import ren.xxpure.entity.LoginUser;
import ren.xxpure.entity.Todo;
import ren.xxpure.service.TodoService;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@RestController
public class TodoController {
	@Resource
	private
	TodoService todoService;

	@ApiOperation("查询满足条件的todo列表 content会执行模糊查询，会根据时间顺序返回结果 时间 格式为yyyy-MM-dd HH:mm:ss")
	@GetMapping("/todo")
	public CommonResult<List<Todo>> todo(Todo todo) {

		return this.todoService.selectList(todo);
	}

	@ApiOperation("查询在时间区间内的todo列表")
	@GetMapping("/todo/between")
	public CommonResult<List<Todo>> todoBetween(@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date start,
	                                            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date end) {

		return this.todoService.selectBetween(start, end);

	}


	@ApiOperation("添加todo 时间 格式为yyyy-MM-dd HH:mm:ss")
	@PostMapping("/todo")
	public CommonResult<Todo> insert(@RequestBody Todo todo) {
		if (todo.getTime() == null) {
			todo.setTime(new Date());
		}
		return this.todoService.save(todo);
	}

	@ApiOperation("修改todo 时间 格式为yyyy-MM-dd HH:mm:ss")
	@PutMapping("/todo")
	public CommonResult<Todo> update(@RequestBody Todo todo) {
		LoginUser principal = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		todo.setUid(principal.getUsername());
		return this.todoService.save(todo);
	}

	@ApiOperation("删除todo")
	@DeleteMapping("/todo")
	public CommonResult<String> delete(String id) {

		return this.todoService.delete(id);
	}
}
